package com.link.play.fit.ai.ui.main.saveFood

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.DocumentChange
import com.google.firebase.firestore.ListenerRegistration
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.toFoodInfoBean
import com.link.play.fit.ai.bean.toRecentlyEatenData
import com.link.play.fit.ai.databinding.SaveFoodLayoutBinding
import com.link.play.fit.ai.databinding.SaveListItemBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_SAVE_FOOD_COLLECT_DATA
import com.link.play.fit.ai.store.CloudStore.deleteList
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.saveFood.details.FixFoodViewmModel
import com.link.play.fit.ai.ui.main.saveFood.details.FoodDtailsAc
import com.link.play.fit.ai.utils.DateEx
import com.link.play.fit.ai.utils.DateEx.getPmDate
import kotlinx.coroutines.launch

class SaveFoodAc : BaseActivity<SaveFoodLayoutBinding>(SaveFoodLayoutBinding::inflate) {
    private var calendarStatusData: CalendarStatusData? = null
    private val listAdapter by lazy { ListAdapter() }
    private var registration: ListenerRegistration? = null

    val viewModel: FixFoodViewmModel by lazy {
        ViewModelProvider(this)[FixFoodViewmModel::class.java]
    }
    private var mCollectList: MutableList<CollectFoodInfoData> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
        initListener()
    }

    private fun initData() {
        binding.savefoodList.setLayoutManager(LinearLayoutManager(this))

        calendarStatusData = intent.getSerializableExtra("bean") as CalendarStatusData?
        lifecycleScope.launch {
            mCollectList = CloudStore.getList<CollectFoodInfoData>(
                DOC_SAVE_FOOD_COLLECT_DATA,
                DOC_SAVE_FOOD_COLLECT_DATA
            ) as MutableList<CollectFoodInfoData>
            mCollectList.reverse()
            binding.savefoodList.adapter = listAdapter
            if (mCollectList.isEmpty()) {
                binding.noneLayout.isVisible = true
                binding.savefoodList.isVisible = false
            } else {
                binding.noneLayout.isVisible = false
                binding.savefoodList.isVisible = true
            }
            "mCollectList  $mCollectList".d()
        }

    }

    private fun initListener() {
        registration = CloudStore.observeList(
            DOC_SAVE_FOOD_COLLECT_DATA,
            DOC_SAVE_FOOD_COLLECT_DATA
        ) { querySnapshot, error ->
            if (error != null) {
                return@observeList
            }
            querySnapshot?.let { snapshot ->
                for (documentChange in snapshot.documentChanges) {
                    when (documentChange.type) {
                        DocumentChange.Type.ADDED -> {
                            val data = documentChange.document.data
                            " DocumentChange.Type.ADDED  ${data}".d()

                        }

                        DocumentChange.Type.MODIFIED -> {
                            // 遍历所有文档
                            for (document in snapshot.documents) {
                                val timeMillisecond = document.getString("timeMillisecond")

                                val index =
                                    mCollectList.indexOfFirst { it.timeMillisecond == timeMillisecond }
                                if (index!=-1){
                                    val collect=document.toObject<CollectFoodInfoData>(CollectFoodInfoData::class.java)
                                    collect?.let {
                                        mCollectList[index] = collect
                                        listAdapter.notifyItemChanged(index)
                                    }
                                }
//                                val servings = document.getDouble("servings")
//                                val carbs = document.getDouble("carbs")
//                                val fats = document.getDouble("fats")
//                                val protein = document.getDouble("protein")
//                                val name = document.getString("name")
//                                val description = document.getString("description")
//                                val calories = document.getDouble("calories")
//
//                                if (index != -1) {
//                                    servings?.let {
//                                        mCollectList[index] =
//                                            mCollectList[index].copy(servings = it)
//                                    }
//                                    carbs?.let {
//                                        mCollectList[index] = mCollectList[index].copy(carbs = it)
//                                    }
//                                    fats?.let {
//                                        mCollectList[index] = mCollectList[index].copy(fats = it)
//                                    }
//                                    protein?.let {
//                                        mCollectList[index] = mCollectList[index].copy(protein = it)
//                                    }
//                                    name?.let {
//                                        mCollectList[index] = mCollectList[index].copy(name = it)
//                                    }
//                                    description?.let {
//                                        mCollectList[index] =
//                                            mCollectList[index].copy(description = it)
//                                    }
//                                    calories?.let {
//                                        mCollectList[index] =
//                                            mCollectList[index].copy(calories = it)
//                                    }
//                                }
                            }
                        }

                        DocumentChange.Type.REMOVED -> {
                            val data = documentChange.document.data
                            "DocumentChange.Type.REMOVED $data".d()
                            val timeMillisecond = data["timeMillisecond"]
                            val index =
                                mCollectList.indexOfFirst { it.timeMillisecond == timeMillisecond }
                            if (index != -1) {
                                mCollectList.removeAt(index)
                                listAdapter.notifyItemRemoved(index)
                            }
                            if (mCollectList.isEmpty()) {
                                binding.noneLayout.isVisible = true
                                binding.savefoodList.isVisible = false
                            } else {
                                binding.noneLayout.isVisible = false
                                binding.savefoodList.isVisible = true
                            }
                        }
                    }
                }
            }
        }
        binding.backImage.setOnClickListener {
            finish()
        }
    }


    inner class ListAdapter : RecyclerView.Adapter<ListAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.save_list_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            kotlin.runCatching {
                holder.itemBinding.nameText.text = mCollectList[position].name
                holder.itemBinding.dateText.text = getPmDate(mCollectList[position].timeMillisecond)

                holder.itemBinding.editImg.setOnClickListener {
                    val p = holder.adapterPosition
                    goToAc(FoodDtailsAc::class.java) {
                        putExtra("bean", calendarStatusData)
                        putExtra("foodBean", mCollectList[p])

                    }
                }
                holder.itemBinding.contentLayout.setOnClickListener {
//                    val data = mCollectList[position].toRecentlyEatenData()
//                        .apply { createTime = mCollectList[position].timeMillisecond }
                    val timestamp = System.currentTimeMillis().toString()
                    val data = mCollectList[position].toRecentlyEatenData().apply {
//                        type = 3
                        createTime = timestamp
                    }

                    //添加到首页
                    CloudStore.addToList(
                        CloudStore.DOC_RECENTLY_LIST_DATA,
                        DateEx.getDayOfMonth(),
                        timestamp,
                        data
                    )
                    //如果是从接口搜索出来的食物的收藏,要添加到最近的列表中
                    val foodInfo= mCollectList[position].toFoodInfoBean()
                    foodInfo?.let {
                        CloudStore.addToList(
                            CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                            CloudStore.DOC_FOOD_DATABASE_RECENTLY_DATA,
                            System.currentTimeMillis().toString(),
                            foodInfo
                        )
                    }
                    goToAc(MainAc::class.java) {
                        putExtra(
                            "logFood",
                            Gson().toJson(data)
                        )
                        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    }
//                    Toast.makeText(this@SaveFoodAc, getString(R.string.Collection_successful), Toast.LENGTH_SHORT).show()

                    //删除
//                    deleteList(
//                        DOC_SAVE_FOOD_COLLECT_DATA,
//                        DOC_SAVE_FOOD_COLLECT_DATA,
//                        mCollectList[position].timeMillisecond
//                    )
                    this@SaveFoodAc.finish()
                }
            }

        }

        override fun getItemCount(): Int {
            return mCollectList.size
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: SaveListItemBinding =
                SaveListItemBinding.bind(itemView)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        registration?.remove()
    }

}